package org.tis.tools.senior.module.developer.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tis.tools.core.web.controller.BaseController;
import org.tis.tools.core.web.vo.SmartPage;
import org.tis.tools.model.common.ResultVO;
import org.tis.tools.senior.module.core.web.util.ShiroUtil;
import org.tis.tools.senior.module.developer.controller.request.*;
import org.tis.tools.senior.module.developer.entity.SBranch;
import org.tis.tools.senior.module.developer.entity.SProfiles;
import org.tis.tools.senior.module.developer.entity.SStandardList;
import org.tis.tools.senior.module.developer.entity.SWorkitem;
import org.tis.tools.senior.module.developer.entity.enums.BranchType;
import org.tis.tools.senior.module.developer.entity.enums.IsAllowDelivery;
import org.tis.tools.senior.module.developer.entity.vo.ProfileBranchDetail;
import org.tis.tools.senior.module.developer.entity.vo.ProjectDetail;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.ISProfilesService;
import org.tmatesoft.svn.core.SVNException;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.text.ParseException;
import java.util.Date;

/**
 * sProfiles的Controller类
 * 
 * @author Auto Generate Tools
 * @date 2018/06/20
 */
@RestController
@RequestMapping("/sProfiles")
@Validated
@Api(value = "运行环境controller", tags = {"运行环境操作接口"})
public class SProfilesController extends BaseController<SProfiles>  {

    @Autowired
    private ISProfilesService sProfilesService;

    /**
     * 新增运行环境
     * @param request
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "新增运行环境")
    @ApiOperation(value = "添加运行环境接口", notes = "body传参")
    @PostMapping
    public ResultVO add(@RequestBody
                            @ApiParam(name = "request", value = "新增运行环境的对象信息", required = true)
                            @Validated({ProfileAddAndUpdateRequest.add.class, Default.class})
                                    ProfileAddAndUpdateRequest request) {
        SProfiles sProfiles = new SProfiles();
        BeanUtils.copyProperties(request,sProfiles);
        EntityWrapper<SProfiles> wrapper = new EntityWrapper<>();
        wrapper.eq(SProfiles.COLUMN_SERIAL_TAG, sProfiles.getSerialTag());
        if (sProfilesService.selectCount(wrapper) > 0) {
            throw new DeveloperException("流水标志" + sProfiles.getSerialTag()  + "已存在");
        }
        sProfiles.setProfilesCode(sProfiles.getProfilesName());
        sProfiles.setIsAllowDelivery(IsAllowDelivery.ALLOW);

        sProfilesService.insert(sProfiles);
        return ResultVO.success("新增成功！", sProfiles);
    }

    /**
     * 修改运行环境接口
     * @param request
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "修改运行环境")
    @ApiOperation(value = "修改运行环境接口", notes = "body传参")
    @PutMapping
    public ResultVO update(@RequestBody
                               @ApiParam(name = "request", value = "修改运行环境的对象信息", required = true)
                               @Validated({ProfileAddAndUpdateRequest.update.class, Default.class})
                                       ProfileAddAndUpdateRequest request) {

        sProfilesService.update(request);
        return ResultVO.success("修改成功！");
    }

    /**
     * 删除运行环境接口
     * @param guid
     * @return
     */
    //@OperateLog(type = OperateType.DELETE, desc = "删除运行环境")
    @ApiOperation(value = "删除运行环境接口", notes = "url传参")
    @DeleteMapping("/{guid}")
    public ResultVO delete(@PathVariable
                               @ApiParam(name = "guid", value = "运行环境guid", required = true)
                               @NotNull(message = "id不能为空")
                                       Integer guid) {
        sProfilesService.deleteProfileAndBranchMapping(guid);
        return ResultVO.success("删除成功");
    }
    
    @GetMapping("/{guid}")
    public ResultVO detail(@PathVariable @NotNull(message = "id不能为空") Integer guid) {
        SProfiles sProfiles = sProfilesService.selectById(guid);
        if (sProfilesService == null) {
            return ResultVO.error("404", "找不到对应记录或已经被删除！");
        }
        return ResultVO.success("查询成功", sProfiles);
    }

    /**
     * 查询已开启运行环境
     *
     * @return
     */
    @ApiOperation(value = "查询开启运行环境", notes = "不传参")
    @GetMapping("/list")
    public ResultVO list() {
        return  ResultVO.success("查询成功", sProfilesService.profilesAll());
    }

    /**
     * 查询所有的运行环境
     * @return
     */
    @ApiOperation(value = "查询所有运行环境", notes = "不传参")
    @GetMapping("/listAll")
    public ResultVO listAll() {
        return ResultVO.success("查询成功", sProfilesService.selectList(null));
    }

    /**
     * 查询所有运行环境及分页
     * @param page
     * @return
     */
    @ApiOperation(value = "查询所有运行环境及分页", notes = "body传参")
    @PostMapping("/all")
    public ResultVO profilesAll(@RequestBody
                                   @ApiParam(name = "page", value = "page对象信息", required = true)
                                   @Validated SmartPage<ProfileBranchDetail> page){

        Page<ProfileBranchDetail> workitemDetailPage = new Page<ProfileBranchDetail>
                (page.getPage().getCurrent(), page.getPage().getSize(),
                        page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功",
                sProfilesService.profileFullPathDetail(workitemDetailPage, getWrapper(page.getCondition())));
    }

    /**
     * 修改运行环境状态
     * @param request
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "修改运行环境状态(是否可投放)")
    @ApiOperation(value = "修改运行环境状态", notes = "body传参")
    @PutMapping("/status")
    public ResultVO updateStatus(@RequestBody @Validated ProfileUpdateStatusRequest request){
        sProfilesService.updateProfileStatus(request.getGuid(), request.getIsAllowDelivery());
        return ResultVO.success("修改成功！");
    }

    /**
     * 关联分支
     * @param profileGuid
     * @param guidBranch
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "运行环境关联分支")
    @ApiOperation(value = "关联分支", notes = "body传参")
    @GetMapping("/{profileGuid}/branch/{guidBranch}")
    public ResultVO relevanceBranch(@PathVariable
                                        @ApiParam(name = "profileGuid", value = "运行环境guid", required = true)
                                        @NotNull(message = "运行环境guid不能为空")
                                                Integer profileGuid,
                                    @PathVariable
                                    @ApiParam(name = "guidBranch", value = "分支guid", required = true)
                                    @NotNull(message = "分支guid不能为空")
                                            Integer guidBranch){
        sProfilesService.profileRelevanceBranch(profileGuid,guidBranch);
        return ResultVO.success("关联成功！");
    }

    /**
     * 取消关联分支
     * @param profileGuid
     * @return
     */
    //@OperateLog(type = OperateType.DELETE, desc = "取消关联分支")
    @ApiOperation(value = "取消关联分支", notes = "url传参")
    @GetMapping("/{profileGuid}/cancel")
    public ResultVO cancelBranch(@PathVariable @NotNull(message = "运行环境id不能为空")Integer profileGuid){
        sProfilesService.profileCancelBranch(profileGuid);
        return ResultVO.success("取消分支成功！");
    }

    /**
     * 根本运行环境guid查询分支信息
     * @param profileGuid
     * @return
     */
    @GetMapping("/{profileGuid}/branchDetail")
    public ResultVO selectBranchDetail(@PathVariable @NotNull(message = "运行环境id不能为空")Integer profileGuid){

        return ResultVO.success("查询成功！",sProfilesService.selectBranchByProfileGuid(profileGuid));
    }

    /**
     * 可关联分支
     * @return
     */
    @GetMapping("/relevanceBranch")
    public ResultVO relevanceBranch(){
        return ResultVO.success("查询成功",sProfilesService.mayRelevanceReleaseBranch());
    }

    /**
     * 查询所有的运行环境给出默认的投放时间及打包窗口
     * @return
     */
    @GetMapping("/packTimeVerify/{guidWorkitem}/delivered")
    public ResultVO packTimeVerify(@PathVariable @NotNull(message = "工作项guid不能为空")Integer guidWorkitem) throws ParseException {

        return ResultVO.success("查询成功",sProfilesService.profileAllPackTimeVerify(guidWorkitem));
    }

    /**
     * 新增环境分支
     * @param guid
     * @param request
     * @return
     * @throws SVNException
     */
    //@OperateLog(type = OperateType.ADD, desc = "新增环境分支")
    @ApiOperation(value = "新增环境分支", notes = "url传参")
    @PostMapping("/{guid}/branch")
    @RequiresRoles("rct")
    public ResultVO addBranch(@PathVariable @NotBlank(message = "环境id不能为空") String guid,
                              @RequestBody @Validated ProfileAddBranchRequest request) throws SVNException {
        SBranch sBranch = new SBranch();
        String fullPath = request.getFullPath().trim();
        if (fullPath.endsWith("/")) {
            sBranch.setFullPath(fullPath.substring(0, fullPath.length() - 1));
        }else{
            sBranch.setFullPath(fullPath);
        }
        sBranch.setBranchFor(request.getBranchFor());
        sBranch.setBranchType(BranchType.RELEASE);
        sBranch.setCreater(ShiroUtil.getUser().getUserId());
        sBranch.setCreateTime(new Date());
        sProfilesService.insertBranch(guid, sBranch);
        return ResultVO.success("新增环境分支成功！");
    }

    /**
     * 获取环境的工程详情
     * @param guid
     * @return
     */
    @GetMapping("/{guid}/project")
    public ResultVO selectProject(@PathVariable @NotNull(message = "运行环境guid不能为空") Integer guid) throws SVNException {
        ProjectDetail result = sProfilesService.selectProjects(guid);
        return ResultVO.success("查询成功！", result);
    }

    /**
     * 拉工程
     * @param guid
     * @param request
     * @return
     * @throws SVNException
     */
    //@OperateLog(type = OperateType.ADD, desc = "拉工程")
    @ApiOperation(value = "拉工程", notes = "url和body传参")
    @PostMapping("/{guid}/project")
    @RequiresRoles("rct")
    public ResultVO addProject(@PathVariable @NotBlank(message = "工作项id不能为空") String guid,
                               @RequestBody @Validated WorkItemAddProjectRequest request) throws SVNException {
        sProfilesService.insertProjects(guid, request.getProjectGuids());
        return ResultVO.success("拉取工程成功！");
    }

    /**
     * 投放到新环境
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "投放到新环境")
    @ApiOperation(value = "投放到新环境", notes = "url传参")
    @GetMapping("/addToNewProfiles/{guidWorkitem}/delivered")
    public ResultVO addToNewProfiles(@PathVariable
                                         @ApiParam(name = "guidWorkitem", value = "工作项guid", required = true)
                                         @NotNull(message = "工作项guid不能为空")
                                                 Integer guidWorkitem){

        return ResultVO.success("查询成功",sProfilesService.addToNewProfile(guidWorkitem));
    }

    /**
     * 查询此运行环境的概况详情
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此运行环境的概况详情", notes = "url传参")
    @GetMapping("/{guid}/general")
    public ResultVO selectPorfilesGeneral(@PathVariable
                                              @ApiParam(name = "guid", value = "运行环境guid", required = true)
                                              @NotNull(message = "运行环境guid不能为空")
                                                      Integer guid){

        return ResultVO.success("查询成功",sProfilesService.selectProfilesGeneral(guid));
    }

    /**
     * 查询此环境下投放过的所有工作项
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此环境下投放过的所有工作项", notes = "url传参")
    @PostMapping("/{guid}/PutWorkitemDetail")
    public ResultVO PutWorkitemDetail(@PathVariable
                                          @ApiParam(name = "guid", value = "运行环境guid", required = true)
                                          @NotNull(message = "运行环境guid不能为空")
                                                  Integer guid,
                                      @RequestBody
                                          @ApiParam(name = "page", value = "分页对象", required = true)
                                          @Validated
                                                  SmartPage<SWorkitem> page){
        Page<SWorkitem> workitemDetailPage = new Page<>
                (page.getPage().getCurrent(), page.getPage().getSize(),
                        page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功",sProfilesService.selectPutWorkitemDetail(
                    guid, workitemDetailPage, getWrapper(page.getCondition())));
    }

    /**
     * 查询指定日期到今天所有的投放申请
     * @return
     */
    @ApiOperation(value = "查询指定日期到今天所有的投放申请", notes = "url传参")
    @GetMapping("/{guid}/DeliveryDay/{number}")
    public ResultVO DeliveryByDay(@PathVariable
                                      @ApiParam(name = "number", value = "查询的天数", required = true)
                                      @NotNull(message = "天数不能为空")
                                              Integer number,
                                  @PathVariable
                                  @ApiParam(name = "guid", value = "运行环境guid", required = true)
                                  @NotNull(message = "运行环境guid不能为空")
                                          Integer guid){

        return ResultVO.success("查询成功", sProfilesService.selectPeriodDeliverysGroupDate(number,guid));
    }

    /**
     * 查询该环境工作项投放的代码
     * @return
     */
    @ApiOperation(value = "查询该环境工作项投放的代码", notes = "url传参")
    @GetMapping("/{guidProfiles}/workitem/{guidWorkitem}")
    public ResultVO selectDeliveryListbyProWorkByGuid(@PathVariable
                                                   @ApiParam(name = "guidWorkitem", value = "工作项的guid", required = true)
                                                   @NotNull(message = "工作项guid不能为空")
                                                           Integer guidWorkitem,
                                                   @PathVariable
                                                   @ApiParam(name = "guidProfiles", value = "运行环境guid", required = true)
                                                   @NotNull(message = "运行环境guid不能为空")
                                                           Integer guidProfiles){

        return ResultVO.success("查询成功",sProfilesService.selectDeliveryDetailByProWorkGuid(guidProfiles,guidWorkitem));
    }

    /**
     * 查询此工作项可以延迟投放代码文件
     * @param guidProfilse
     * @return
     */
    @ApiOperation(value = "查询此工作项可以延迟投放代码文件")
    @PostMapping("/{guidProfilse}/profiles/{guidWorkitem}/standardList")
    public ResultVO standardList(@PathVariable
                                    @ApiParam(name = "guid", value = "运行环境guid", required = true)
                                    @NotNull(message = "运行环境guid不能为空")
                                            Integer guidProfilse,
                                    @PathVariable
                                    @ApiParam(name = "guid", value = "工作项guid", required = true)
                                    @NotNull(message = "工作项guid不能为空")
                                            Integer guidWorkitem,
                                    @RequestBody
                                    @ApiParam(name = "page", value = "分页对象", required = true)
                                    @Validated
                                            SmartPage<SStandardList> page){
        Page<SStandardList> sStandardListPage = new Page<>
                (page.getPage().getCurrent(), page.getPage().getSize(),
                        page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功", sProfilesService.selectStandardByItemGuidProGuid(guidProfilse,
                            guidWorkitem, sStandardListPage,getWrapper(page.getCondition())));
    }

    /**
     * 更新环境是否允许延期的状态,所有环境只允许一个环境为允许延期
     * @param req
     * @return
     */
    @ApiOperation(value = "更新环境是否允许延期的状态")
    @PostMapping("/updateRepeal")
    public ResultVO updateRepeal(@RequestBody @Validated  ProfileUpdateIsRepeal req){
        return ResultVO.success("更新成功",sProfilesService.updateRepeal(req));
    }

    /**
     * 将环境代码checkout到本地
     * @param guidProfiles
     * @return
     */
    @ApiOperation(value = "将环境代码checkout")
    @GetMapping("/{guidProfiles}/checkoutCode")
    public ResultVO checkoutCode(@PathVariable
                                 @ApiParam(name = "guid", value = "运行环境guid", required = true)
                                 @NotNull(message = "运行环境guid不能为空")
                                         Integer guidProfiles) throws SVNException {
        sProfilesService.checkoutCode(guidProfiles);
        return ResultVO.success("代码下载成功!");
    }

}

